﻿using System;

namespace DotNetCommon.Validate.Annotations;

/// <summary>
/// 限定最小长度, 示例:
/// <code>
/// [VMinLength(10)]
/// public string Slogan { get; set; }
/// </code>
/// </summary>
/// <remarks>注意: 当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMinLengthAttribute(int min, string errorMessage = null) : Attribute, IValidateAction
{
    public int Min { get; set; } = min;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        ValidateStringExtensions.MustMinLengthInternal(ctx, ctx.ModelValue?.ToString(), Min, ErrorMessage);
    }
}

/// <summary>
/// 如果不为null, 则限定最小长度, 示例:
/// <code>
/// [VMinLengthIfNotNull(10)]
/// public string Slogan { get; set; }
/// </code>
/// </summary>
/// <remarks>注意: 当属性不是字符串时, 会先调用 ToString() 转为字符串再进行判断, 这可以用于对非字符串类型的校验</remarks>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public sealed class VMinLengthIfNotNullAttribute(int min, string errorMessage = null) : Attribute, IValidateAction
{
    public int Min { get; set; } = min;
    public string ErrorMessage { get; set; } = errorMessage;

    public void Action(IValidateContext ctx)
    {
        if (ctx.ModelValue == null) return;
        ValidateStringExtensions.MustMinLengthInternal(ctx, ctx.ModelValue?.ToString(), Min, ErrorMessage);
    }
}
